package app.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zhou.ExcelExportor;

import app.entity.WorkCard;
import app.entity.WorkCardTemp;
import siotwx.dao.EventlogDao;
import siotwx.dao.FacinfoDao;
import siotwx.dao.ModuleDao;
import siotwx.dao.UserDao;
import siotwx.entity.Eventlog;
import siotwx.entity.Facinfo;
import siotwx.entity.Module;
import siotwx.entity.User;
/**
 *  该类用来处理与工单相关的一系列操作
 *  
 * @author 周超 2018年3月12日
 *
 */
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
@Service("WorkCardService")
public class WorkCardService {
	@Autowired
	@Qualifier("EventlogDao")
	private EventlogDao eventlogDao;
	
	@Autowired
	@Qualifier("ModuleDao")
	private ModuleDao moduleDao;
	
	@Autowired
	@Qualifier("UserDao")
	private UserDao userDao;
	
	@Autowired
	@Qualifier("FacinfoDao")
	private FacinfoDao facInfoDao;

	// 将工单预添加到缓存中
	@Transactional(readOnly=true)
	public Integer addToCache(Integer facid,Integer type, HttpSession session) {
		List<WorkCardTemp> workCardList = (List<WorkCardTemp>) session.getAttribute("workCard");
		// 判断工单是否为空
		if (workCardList == null) {
			workCardList = new ArrayList<>();
		}
		//通过传入参数构建预定义工单
		Module module = moduleDao.get(type);
		Map<String, Object> params=new HashMap<>();
		params.put(Facinfo.FieldName.facId.toString(), facid);
		List<Facinfo> list = facInfoDao.getlist(params);
		WorkCardTemp workCardTemp = new WorkCardTemp();
		if (list != null && list.size() > 0) {
			Facinfo facinfo = list.get(0);
			workCardTemp.setFacArea(facinfo.getFacArea());
			workCardTemp.setFacDes(facinfo.getFacDes());
			workCardTemp.setFacId(facinfo.getFacId());
			workCardTemp.setFacNEname(facinfo.getFacNEname());
			workCardTemp.setUserName(facinfo.getUserName());
			workCardTemp.setUserId(facinfo.getUserId());
			workCardTemp.setTel(facinfo.getTel());
			workCardTemp.setType(module.getName());
		}
		
		//执行加入缓存
		int count = 0;
		if (workCardTemp!=null) {
			workCardList.add(workCardTemp);
			count++;
		}
		session.setAttribute("workCard", workCardList);

		return count;
	}
	//获取缓存中的工单列表
	@Transactional(readOnly=true)
	public WorkCardBean workCardList(Integer pageNum, Integer pageSize,HttpSession session,HttpServletResponse response){
		List<WorkCardTemp> workCardList = (List<WorkCardTemp>) session.getAttribute("workCard");
		if (workCardList==null||workCardList.size()==0) {
			return new WorkCardBean();
		}
		//数据不空
		//进行分页处理
		if (pageNum==null||pageNum<1) {
			pageNum=1;
		}
		if (pageNum>(int)Math.ceil(workCardList.size()*1D/pageSize)) {
			pageNum=(int) Math.ceil(workCardList.size()*1D/pageSize);
		}
		
		List<WorkCardTemp> res = workCardList.subList((pageNum-1)*pageSize,
				((pageNum*pageSize)>workCardList.size()?workCardList.size():(pageNum*pageSize)));

		return new WorkCardBean(res, workCardList.size(), pageNum);
	}
	//这是获取工单列表的翻页处理的返回结构bean
	public class WorkCardBean{
		private List<WorkCardTemp> res=new ArrayList<>();
		private Integer total=0;
		private Integer page=1;
		public WorkCardBean() {}
		public WorkCardBean(List<WorkCardTemp> res, Integer total, Integer page) {
			this.res = res;
			this.total = total;
			this.page = page;
		}
		public List<WorkCardTemp> getRes() {
			return res;
		}
		public void setRes(List<WorkCardTemp> res) {
			this.res = res;
		}
		public Integer getTotal() {
			return res.size();
		}
		public void setTotal(Integer total) {
			this.total = total;
		}
		public Integer getPage() {
			return page;
		}
		public void setPage(Integer page) {
			this.page = page;
		}
		
	}
	
	// 从缓存中移除指定工单

	@Transactional(readOnly=true)
	public Integer removeWorkCard(long workCardFlag, HttpSession session) {
		List<WorkCardTemp> workCardList = (List<WorkCardTemp>) session.getAttribute("workCard");
		if (workCardList == null || workCardList.size() == 0) {
			return 0;
		} else {
			for (int index = 0; index < workCardList.size(); index++) {
				if (workCardList.get(index).getTimeTab() == workCardFlag) {
					workCardList.remove(index);
					break;
				}
			}
			session.setAttribute("workCard", workCardList);
			return 1;
		}
	}

	// 将缓存中的工单进行提交处理
	@Transactional(readOnly=false)
	public InputStream commitWorkCard(HttpSession session) throws Exception {
		InputStream input = WorkCardService.class.getResourceAsStream("/temp.xlsx");
		List<WorkCardTemp> workCardList = (List<WorkCardTemp>) session.getAttribute("workCard");
		if (workCardList == null || workCardList.size() == 0) {
			return input;
		} else {
			List<WorkCard> list = new ArrayList<>();
			for (WorkCardTemp workCard : workCardList) {
				if (workCard.getInsId() == null || "".equals(workCard.getInsId())) {
					continue;
				}
				list.add(new WorkCard(workCard.getFacArea(),
						workCard.getFacDes(),
						workCard.getUserName(),
						workCard.getTel(),
						workCard.getInsName(),
						workCard.getInsTel(),
						workCard.getType()));
			}
			if (list.size() > 0) {
				input = new ExcelExportor().getExcel(list);
			}
			//解决数据库存储问题
			for (WorkCardTemp w : workCardList) {				
				if (w.getInsId()==null || "".equals(w.getInsId())) {
					continue;
				}
				List<Module> mt = moduleDao.getlist(null);
				// 获取可用的模块类型
				Module tt = null;
				for (Module m : mt) {
					if (m.getName().equals(w.getType())) {
						tt = m;
						break;
					}
				}
				if (tt != null) {
					eventlogDao.insert(new Eventlog(0,
							tt.getId(), //
							0,
							w.getFacId(), //
							Integer.valueOf(w.getInsId()), //
							2,
							1, // 1
							"",
							"",
							"",
							"0", // 0
							System.currentTimeMillis(), // now
							System.currentTimeMillis() + 3600 * 24 * 1000, // 3t
							"",
							""));
				}
			}
			session.setAttribute("workCard", null);
			return input;
		}
	}
	//给工单指定安装人
	@Transactional(readOnly=false)
	public Integer selectUser(long workCardFlag,Integer userID,HttpSession session){
		List<WorkCardTemp> object = (List<WorkCardTemp>) session.getAttribute("workCard");
		if (object == null) {
			return 0;
		}
		User user = userDao.get(userID);
		for (int i = 0; i < object.size(); i++) {
			if (object.get(i).getTimeTab() == workCardFlag) {
				object.get(i).setInsId(user.getId() + "");
				object.get(i).setInsName(user.getRealName());
				object.get(i).setInsTel(user.getPhoneNumber());
				break;
			}
		}
		return 1;
	}
	
	//删除指定工单
	@Transactional(readOnly=false)
	public Integer delWorlCard(Integer id){
		Integer delete = eventlogDao.delete(id);
		
		
		return delete;
	}
	
}
